package com.itheima.d7_tcp4;

import java.io.*;
import java.net.Socket;

public class ServerThred implements Runnable {
    Socket s;

    public ServerThred(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        while (true) {
            // 3、从socket通信管道中得到一个字节输入流。
            try {
                InputStream is = null;

                is = s.getInputStream();
                // 4、把原始的字节输入流包装成高效的输入流
                InputStreamReader isr = new InputStreamReader(is);
                // 5、使用数据输入流读取客户端发送过来的消息
                br = new BufferedReader(isr);
                // 6、释放资源
                while (true) {
                    String line = br.readLine();
                    if (line == null) {
                        Server.list.remove(s);
                        break;
                    }
                    System.out.println("您有一条新消息 : " + line + s.getInetAddress());
                    for(Socket otherSocket : Server.list) {
                        if(otherSocket != s){
                            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(otherSocket.getOutputStream()));
                            bw.write(line);
                            bw.newLine();
                            bw.flush();
                        }
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                s.close();
                br.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
//            ssc.close();
        }
    }
}
